package com.example.neutonote2.ui.notes;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.neutonote2.R;
import com.example.neutonote2.data.model.NoteWithTags;
import com.example.neutonote2.data.model.Tag;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.NoteViewHolder> {

    private List<NoteWithTags> notes;
    private final OnNoteItemClickListener listener;
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());

    public interface OnNoteItemClickListener {
        void onNoteClick(NoteWithTags noteWithTags);
    }

    public NotesAdapter(List<NoteWithTags> notes, OnNoteItemClickListener listener) {
        this.notes = notes;
        this.listener = listener;
    }

    @NonNull
    @Override
    public NoteViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_note, parent, false);
        return new NoteViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull NoteViewHolder holder, int position) {
        NoteWithTags noteWithTags = notes.get(position);
        holder.bind(noteWithTags);
    }

    @Override
    public int getItemCount() {
        return notes.size();
    }

    public void updateNotes(List<NoteWithTags> newNotes) {
        this.notes = newNotes;
        notifyDataSetChanged();
    }
    
    public List<NoteWithTags> getNotes() {
        return new ArrayList<>(notes);
    }

    class NoteViewHolder extends RecyclerView.ViewHolder {
        private final TextView titleTextView;
        private final TextView contentPreviewTextView;
        private final TextView dateTextView;
        private final TextView categoryTextView;
        private final ChipGroup tagsChipGroup;

        NoteViewHolder(View itemView) {
            super(itemView);
            titleTextView = itemView.findViewById(R.id.text_note_title);
            contentPreviewTextView = itemView.findViewById(R.id.text_note_preview);
            dateTextView = itemView.findViewById(R.id.text_note_date);
            categoryTextView = itemView.findViewById(R.id.text_note_category);
            tagsChipGroup = itemView.findViewById(R.id.chip_group_tags);

            itemView.setOnClickListener(v -> {
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION && listener != null) {
                    listener.onNoteClick(notes.get(position));
                }
            });
        }

        void bind(NoteWithTags noteWithTags) {
            titleTextView.setText(noteWithTags.note.getTitle());
            
            // 截取内容前100个字符作为预览
            String content = noteWithTags.note.getContent();
            if (content != null && content.length() > 100) {
                content = content.substring(0, 100) + "...";
            }
            contentPreviewTextView.setText(content);
            
            // 格式化日期
            Date modifiedDate = noteWithTags.note.getModifiedTime();
            if (modifiedDate != null) {
                dateTextView.setText(dateFormat.format(modifiedDate));
            } else {
                dateTextView.setText("");
            }
            
            // 设置分类
            String category = noteWithTags.note.getCategory();
            if (category != null && !category.isEmpty()) {
                categoryTextView.setVisibility(View.VISIBLE);
                categoryTextView.setText(category);
            } else {
                categoryTextView.setVisibility(View.GONE);
            }
            
            // 清除现有标签
            tagsChipGroup.removeAllViews();
            
            // 添加标签
            if (noteWithTags.tags != null && !noteWithTags.tags.isEmpty()) {
                tagsChipGroup.setVisibility(View.VISIBLE);
                
                // 最多显示3个标签
                int maxTags = Math.min(noteWithTags.tags.size(), 3);
                for (int i = 0; i < maxTags; i++) {
                    Tag tag = noteWithTags.tags.get(i);
                    Chip chip = new Chip(itemView.getContext());
                    chip.setText(tag.getName());
                    chip.setChipBackgroundColorResource(getTagColorResource(tag.getColor()));
                    chip.setTextColor(itemView.getContext().getResources().getColor(android.R.color.black));
                    chip.setTextSize(10);
                    chip.setClickable(false);
                    tagsChipGroup.addView(chip);
                }
                
                // 如果有更多标签，添加"+N"的提示
                if (noteWithTags.tags.size() > 3) {
                    Chip moreChip = new Chip(itemView.getContext());
                    moreChip.setText("+" + (noteWithTags.tags.size() - 3));
                    moreChip.setChipBackgroundColorResource(android.R.color.darker_gray);
                    moreChip.setTextColor(itemView.getContext().getResources().getColor(android.R.color.black));
                    moreChip.setTextSize(10);
                    moreChip.setClickable(false);
                    tagsChipGroup.addView(moreChip);
                }
            } else {
                tagsChipGroup.setVisibility(View.GONE);
            }
        }
        
        // 根据标签颜色字符串获取对应的颜色资源ID
        private int getTagColorResource(String colorString) {
            try {
                // 尝试解析颜色字符串
                android.graphics.Color.parseColor(colorString);
                // 如果成功解析，就在运行时设置这个颜色
                return android.R.color.transparent; // 这个值不会被使用，因为我们会在bindViewHolder中直接设置颜色
            } catch (Exception e) {
                // 如果解析失败，返回一个默认颜色
                return android.R.color.holo_blue_light;
            }
        }
    }
} 